<?php
namespace controller;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ShopAdmin_Contact
 *
 * @author Damian
 */
class ShopAdmin_Contact extends Seller{
   public function index() {
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Pytania od klientów");
        $conversationsCriteria = new \model\Criteria();
        $conversationsCriteria->from(\model\TblConversation::getModel()->getTable())
                ->where(\model\TblConversation::SHOP_ID, "=", $this->shop->ShopID,  \model\TblConversation::getModel()->getTable())
                ->join(\model\TblCustomer::getModel())
                ->join(\model\TblPerson::getModel());
        $Conversations = \model\TblConversation::getModel()->all($conversationsCriteria);
        $view = $this->getActionView();
        if ($Conversations){
            $maxID=0;
            $conversationsCount=0;
            $view->set("conversations",$Conversations);
            $messagesConv=array();
            $unreadConv = array();
            foreach ($Conversations as $conv){
                $conversationsCount++;
                $messageCriteria = new \model\Criteria();
                $messageCriteria->from(\model\TblAnswer::getModel()->getTable())
                        ->where(\model\TblAnswer::CONVERSATION_ID, "=",$conv->ConversationID)
                        ->order(\model\TblAnswer::ADDITION_DATE,"Asc");
                $messageCountCriteria = new \model\Criteria();
                $messageCountCriteria->from(\model\TblAnswer::getModel()->getTable())
                        ->where(\model\TblAnswer::CONVERSATION_ID, "=",$conv->ConversationID)
                        ->where(\model\TblAnswer::SEND_BY_CUSTOMER,"=",1,false, " and ")
                        ->where(\model\TblAnswer::SEEN,"=",0,false, " and ");
                $messages = \model\TblAnswer::getModel()->all($messageCriteria);
                $messagesConv[$conv->ConversationID]=$messages;
                $unreadConv[$conv->ConversationID]=$messageCountCriteria->count();
                if ($messages[sizeof($messages)-1]->AnswerID>$maxID){
                    $maxID=$messages[sizeof($messages)-1]->AnswerID;
                }
            }
            $view->set("unreadConv",$unreadConv);
            $view->set("maxID",$maxID);
            $view->set("coversationsCount",$conversationsCount);
            $view->set("messages",$messagesConv);
        }
        $this->render();
    }
}
